package ar.com.candoit.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.com.candoit.beans.Student;

@Repository()
public class StudentDaoImpl implements StudentDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void saveStudent(Student student) {
		sessionFactory.getCurrentSession().save(student);
	}

	@SuppressWarnings("unchecked")
	public List<Student> listStudent() {
		return sessionFactory.getCurrentSession().createQuery("from Student")
				.list();
	}

	public Student findStudentByName(String student_name) {

		return (Student) sessionFactory.getCurrentSession()
				.createCriteria(Student.class)
				.add(Restrictions.eq("studentName", student_name))
				.uniqueResult();
	}

	@Override
	public Student findStudentById(long student_id) {
		return (Student) sessionFactory.getCurrentSession()
				.createCriteria(Student.class)
				.add(Restrictions.eq("studentId", student_id)).uniqueResult();
	}

	@Override
	public void updateStudent(Student student) {
		String hql = "update Student set studentName = :studentName, adressid = :adressid where studentId = :studentId";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString("studentName", student.getStudentName());
		query.setLong("studentId", student.getStudentId());
		query.setParameter("adressid", student.getAdress().getAdressid());
		query.executeUpdate();
	}

	@Override
	public void deleteStudent(Student student) {
		String hql = "delete from Student where student_id = :student_id";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString("student_id", String.valueOf(student.getStudentId()));
		query.executeUpdate();
	}

}